import React from 'react';
import {connect} from 'dva'

import Title from 'components/Title'
import { CommAbstract } from 'components/Abstract'

import { config } from 'utils'
const { scada } = config;
const {
  Token,
  realtimeIndicators,
} = scada;

@connect(({monitor}) => ({...monitor}))
class Indicators extends React.Component {
  List = realtimeIndicators;

  constructor(props) {
    super(props);

    this.state = {
      dataSource: {},
    }
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    await this.setDateStatistics()
  }

  setDateStatistics = async () => {
    const { List } = this;
    List.map(ele => {
      this.queryData(ele);
    })
  }

  queryData = async (tab) => {
    const { serverType } = tab;
    // hd_station_list时，直接list请求
    if (serverType === "hd_station_list") {
      await this.queryStationList(tab)
    } else {
      // 1. 先调用 queryUbizTpl，获取 columns 字段信息
      await this.queryUbizTpl(tab)
      .then((result) => {
        // 2. 再 获取的columns信息传入下次请求
        const { columns } = result;
        this.queryScadaTpl(tab, columns)
      })
    }
  }

  // station list
  queryStationList = async (param) => {
    const { value, payload } = param;
    let server = { type: 'monitor/queryList' }
    Object.assign(payload, { Token, value: `Indicators${value}` })
    Object.assign(server, { payload })
    await this.props.dispatch(server)
  }
  // Ubiz Tpl
  queryUbizTpl = async (param) => {
    const { value } = param;
    let server = { type: 'monitor/queryUbizTpl' };
    const payload = {
      Token, "conditions": [{ Field: "code", Operate: "=", Value: value, Relation: "and" }], order: [], size: 20, index: 1
    }
    Object.assign(payload, { value: `Indicators${value}` })
    Object.assign(server, { payload })
    // 注意：return后，可以回调哦！
    return await this.props.dispatch(server)
  }
  // Scada Tpl
  queryScadaTpl = async (param, columns) => {
    const { value, payload } = param;

    // 处理 columns 开始
    let columnsParams = {}
    columns.forEach(column => {
      const { id, attribute, type } = column;
      // columns值：attribute 和 type的拼接
      let cols = attribute;
      Object.assign(cols, { "_type": type })
      // columns键名：'C' + id 拼接
      columnsParams[`C${id}`] = cols;
    })
    // 处理 columns 结束

    Object.assign(payload, { Token, value: `Indicators${value}`, columns: columnsParams });
    await this.props.dispatch({
      type: 'monitor/queryScadaTpl',
      payload
    })
  }

  renderIndicators = () => {
    const { props, List } = this;
    let dataSource = {}
    
    
    List.map(list => {
      const { value, serverType } = list;

      if (serverType === "hd_station_list") {
        const dataResource = props[`ListResourceIndicators${value}`];
        let total = 0;
        let alarmNum = 0;
        try {
          if(dataResource){
            // TODO：
            total = 1;
            alarmNum = 0;
          }
          const status = alarmNum >0 ? false: true;
          dataSource[value] = { total, alarmNum, status }
        } catch (error) {
          console.error(error)
        }
      } else {
        const dataResource = props[`ScadaTplResourceIndicators${value}`];
        try {
          let total = 0;
          let alarmNum = 0;
          if (Array.isArray(dataResource)) {
            dataResource.map((item) => {
              // alarming=true 在报警
              const { alarming } = item;
              if(alarming === true) alarmNum++;
              total++
            })
          }
          // 如果 报警数大于0，则为 异常（false）
          const status = alarmNum >0 ? false: true;
          dataSource[value] = { total, alarmNum, status }
        } catch (error) {
          console.error(error)
        }
      }
    })

    const options = [
      { vField: 'total', tField: '数量' },
      { vField: 'status', tField: '运行状态' },
      { vField: 'alarmNum', tField: '异常设备' },
    ];
    return (<CommAbstract
      columns={this.List}
      dataSource={dataSource}
      options={options}
      type={'2'}
      isColorful={true}
      className={'col-12'}/>)
  }

  render() {
    // const { dataSource } = this.state;
    return (<Title title={'重点指标监控'}  style={{'padding': '2%'}}>
        {this.renderIndicators()}
      </Title>)
  }
}

export default Indicators;
